<template>
  <div>
    <div class="brandActivityTop">
      <img v-if="extendObj.has_image" :src="extendObj.image_url +'?x-oss-process=image/quality,Q_80/format,jpg'" mode="widthFix"  @load="imageLoad">
      <div v-if="extendObj.has_text" class="text">{{extendObj.text}}</div>
    </div>
    <div class="tab-bar" :class="{'tabpr':tabprTf}">
      <div @click="popupSorter">排序</div>
      <div @click="popupCondition">筛选</div>
    </div>

    <div class="product-list" :class="{'marginTop':tabprTf}">
      <productItem v-for="productinfo in productList" :key="productinfo.product_id"
                   :product="productinfo"></productItem>

      <div class="spinnerBox" :hidden="footerHide">
        {{loadMoreText}}
        <div class="spinner" v-if="hasMore">
          <div class="bounce1"></div>
          <div class="bounce2"></div>
          <div class="bounce3"></div>
        </div>
      </div>
    </div>
    <sorter v-if="sorterShow" :data="sorterData" :selectSortIndex="currentSortIndex"
            @receiveSorter="changeSorter" :styleTop="sorterHeight" @popupSorter="popupSorter"></sorter>
    <placeholder :show.sync="isPageEmpty" :message.sync="emptyMsg" :hidBtn="hidBtn" @tryAgain="onTap" :styleTop="44"/>
  </div>

</template>

<script>
  import {mapState, mapMutations, mapActions} from "vuex";
  import placeholder from '@/components/placeholder'
  import productItem from '@/components/product-item'
  import sorter from '@/components/sorter'
  import tools from '@/store/tools'
  import pullmixin from '@/mixins/PullRefreshLayout'
  import common from '@/utils/common'
  import Arrayutils from '@/utils/arrayutils'
  import {getGoodsList, getGoodsListWithNoProgress} from '@/net/commonapi'
  import {cateAction2,brandAction2,productListTopAction} from '@/store/funnames'

  export default {
    data() {
      return {
        from: 1,
        sorterShow: false,
        productList: [],
        sorterData: [],
        scrollHeight: 0,
        currentSortIndex: 0,
        promotion:'',
        extendObj:'',
        promotionHeight:0,
        sorterHeight:0,
        tabprTf:true,
        scrollFlag:true,
        isFirst: true,
      };
    },
    mixins: [pullmixin],
    computed: {
      ...mapState('cate2', ['selectFemaleCateList', 'selectBrandList', 'priceData', 'selectManCateList', 'otherPrams', 'word', 'sortType', 'sortId', 'promotionId']),
      ...mapState('productListTop', ['productListTop'])
    },
    onLoad() {
      this.scrollHeight = common.getWindowHeight() - 40
      this.getSorter()
    },
    onShow() {
      if (!this.isFirst) {
        if (!this.$wx.isArrayEmpty(this.productListTop)) {
          this.extendObj = this.productListTop[this.productListTop.length - 1]
          this.isFirst = false
        }
      }
    },
    onUnload() {
      this.sorterShow = false
      this.tabprTf = true
      this.currentSortIndex = 0
      this.scrollFlag = true
      this.extendObj = '';
      this.updateSort({
        sortType: 1,
        sortId: 1,
      })
      this.topImgDelete()
    },
    onPageScroll (e) {
      if(!this.scrollFlag){
        return
      }
      console.log(e.scrollTop +'--'+ this.promotionHeight)
      if(e.scrollTop > this.promotionHeight){
        this.tabprTf = false
        this.sorterHeight = 44
      } else{
        this.tabprTf = true
        this.sorterHeight = (this.promotionHeight - e.scrollTop) + 44
      }
    },
    mounted() {
      this.reset()
      this.resetBrand()
      let promotionId = this.$root.$mp.query.promotionId;
      if(promotionId){
        this.isFirst = true
        this.getPromotion(promotionId)
      } else{
        this.tabprTf = false
        this.scrollFlag = false
        this.extendObj = '';
        this.topImgAdd(this.extendObj)
      }
      this.updatePromotionId({promotionId: this.$root.$mp.query.promotionId})
      this.updateWord({word: this.$root.$mp.query.word})
      if (!this.$wx.isEmpty(this.$root.$mp.query.brandId)) {
        this.updateBrand({value: this.$root.$mp.query.brandId})
      }
      this.$wx.setTitleBarTitle(this.$root.$mp.query.title)
      console.log('mounted', this.$root.$eventHub)
      this.getdata(true)
      if (this.$wx.isArrayEmpty(this.$root.$eventHub._events.requestGoods2)) {
        this.$root.$eventHub.$on('requestGoods2', (target) => {
          this.onRefresh(target, false)
        });
      }
    },
    methods: {
      ...mapMutations('cate2', {
        updateSort: cateAction2.ACTION_SORT_UPDATE,
        updatePromotionId: cateAction2.ACTION_SET_PROMOTION_ID,
        reset: cateAction2.ACTION_RESET,
        updateBrand: cateAction2.ACTION_SELECT_BRAND,
        updateWord: cateAction2.ACTION_WORD_UPDATE
      }),
      ...mapMutations('brand2', {
        resetBrand: brandAction2.ACTION_RESET,
      }),
      ...mapMutations('productListTop', {
        topImgAdd: productListTopAction.ACTION_PRODUCT_TOP_ADD,
        topImgDelete: productListTopAction.ACTION_PRODUCT_TOP_DELETE
      }),
      imageLoad: function(e) {
        this.getPromotionHeight()
      },
      getPromotionHeight(){
        var query = wx.createSelectorQuery();
        var that = this;
        query.selectAll('.brandActivityTop').boundingClientRect((rect)=>{
          console.log(rect[0])
          this.promotionHeight = rect[0].height
          this.sorterHeight = rect[0].height + 44
        }).exec();
      },
      onRefresh(isRefresh, showProgress) {
        this.getdata(isRefresh, showProgress)
      },
      popupSorter() {
        this.sorterShow = !this.sorterShow
      },
      async getPromotion(promotionId) {
        const data = await this.$fly.get(this.$url.URL_PROMOTION+'/'+promotionId)
        if (data.successCode === 1) {
          this.isFirst = false
          this.promotion = data.data.promotion;
          this.extendObj = JSON.parse(this.promotion.extend)
          this.topImgAdd(this.extendObj)
        }
      },
      async getSorter() {
        const data = await this.$fly.post(this.$url.URL_SORTER)
        if (data.successCode === 1) {
          this.sorterData = data.data
        }
      },
      async getdata(isRefresh, showProgress) {
        let params = tools.getAllCondition({
          selectBrandList: this.selectBrandList,
          selectFemaleCateList: this.selectFemaleCateList,
          selectManCateList: this.selectManCateList,
          otherPrams: this.otherPrams,
          price: this.priceData,
          word: this.word,
          sort_type: this.sortType,
          sort_id: this.sortId,
          promotion_id: this.promotionId,
          page_index: isRefresh
            ? (this.paramsDatas.pageIndex = 1)
            : this.paramsDatas.pageIndex,
          page_size: this.paramsDatas.pageSize
        })
        const resData = await (showProgress ? getGoodsList(params) : getGoodsListWithNoProgress(params))
        if (resData.successCode) {
          this.preHandler(isRefresh, this.$wx.isArrayEmpty(resData.data.products) ? 0 : resData.data.products.length)
          if (isRefresh) {
            this.productList = resData.data.products
            if (this.$wx.isArrayEmpty(this.productList)) {
              this.isPageEmpty = true
              this.hidBtn = true
              this.emptyMsg = "很抱歉，没有找到想要的商品"
            } else {
              this.isPageEmpty = false
            }
          } else {
            this.productList.push.apply(this.productList, resData.data.products)
          }
        } else {
          this.handlerFail(isRefresh, resData)
        }
      },
      changeSorter(val) {
        this.sorterShow = false;
        this.currentSortIndex = Arrayutils.findIndex(this.sorterData, val)
        this.updateSort({
          sortType: val.sort_type,
          sortId: val.sort_id,
        })
        this.productList = []
        this.onRefresh(true)
      },
      popupCondition() {
        this.$wx.jumper('../categorysinner2/main')
      },
      onTap() {
        this.onRefresh(true)
      },
    },
    destroyed() {
      this.$root.$eventHub.$off('requestGoods2')
    },
    components: {
      productItem,
      sorter,
      placeholder
    }
  };
</script>

<style scoped>
.tabpr{position: relative;}
.marginTop{margin-top: 0}
.brandActivityTop img{ width: 100%; display: block;}
</style>
